package lwk.thread.syn;

/**
 * @author:lwk
 * @create: 2022-08-03 19:27
 * @Description: 线程不安全的买票
 */
public class UnsafeBuyTicket {
    public static void main(String[] args) {
        BuyTicket station = new BuyTicket();

        new Thread(station,"张三").start();
        new Thread(station,"李四四").start();
        new Thread(station,"王五五五").start();

    }
}

class BuyTicket implements Runnable{
    // 票数
    private int ticketNums = 10;
    boolean flag = true; // 外部停止方式
    @Override
    public void run() {
        // 买票
        while (flag) {
            try {
                buy();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    private void buy() throws InterruptedException {

        // 判断是否有票
        if (ticketNums<=0) {
            flag = false;
            return;
        }

        // 模拟延时
        Thread.sleep(100);

        // 买票
        System.out.println(Thread.currentThread().getName()+"买到---"+ticketNums--);
    }

}